<script setup lang="ts">
import { ref } from "vue"
import {$t} from '#/locales'
import { createOrgApi, uploadTplFileApi } from '#/api/system/orgMgr'
import Download from "#/components/download.vue"

defineOptions({ name: 'BatchUploadDialog' })
const titleTxt = $t('common.batchNewTxt')

const emit = defineEmits(['queryTable'])
const obs = {
  Key: 'import/*.xlsx',
};

const blobConfig = {
  type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
};

const submitLoading = ref(false)
const dialogVisible = ref(false)
const formRef = ref()
const defaultFormInline = {
  file: null,
}
const formInline = ref({...defaultFormInline})
const handleClose = () => {
  formInline.value = {...defaultFormInline}
  formRef.value.resetFields()
  dialogVisible.value = false
}

const inint = () => {
  dialogVisible.value = true
}

const submit = () => {
  if (!formRef) return
  formRef.value?.validate((valid:any) => {
    if (valid) {
     let params = {
      file: formInline.value.file,
    } as any
      submitLoading.value = true
      createOrgApi(params).then(() => {
        emit('queryTable')
        handleClose()
      }).finally(() => {
        submitLoading.value = false
      })
    }
  })
}

const handleUpload = async (options: any) => {
  try {
    const { file } = options;
    const formData = new FormData();
    formData.append('file', file);
    await uploadTplFileApi(formData);
  } catch (error) {
  }
};

defineExpose({ inint })

</script>
<template>
  <el-dialog v-model="dialogVisible" :destroy-on-close="true" :title="titleTxt" width="500" :append-to-body="true"
    :close-on-click-modal="false" :before-close="handleClose">
      <el-form ref="formRef" :model="formInline" label-width="1px">
        <el-form-item label=" " prop="file">
          <el-upload
            ref="upload"
            class="upload-demo"
            action="#"
            :limit="1"
            :http-request="handleUpload"
            accept=".xlsx, .xls"
            :auto-upload="false"
          >
            <template #trigger>
              <el-button type="primary">{{$t('common.uploadFileTxt')}}</el-button>
            </template>
            <div class="inline-block ml-[10px] inline-flex items-center">
              <span class="text-[#595959]">{{$t('common.tipNoTplTxt')}}</span>
              <Download class="mr-[10px]" :downloadName="$t('common.downloadTplFileTxt')" :type="'primary'" :link="true" :obs="obs" :blobConfig="blobConfig" />
            </div>
            </el-upload>
        </el-form-item>
      </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">
          {{$t('common.cancelTxt')}}
        </el-button>
        <el-button type="primary" @click="submit" :loading="submitLoading">
          {{$t('common.submitTxt')}}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="less" scoped>
  .el-button.is-link{
    @apply text-[#0067d1];
  }
</style>
